package cn.t222.controller.sys;

import cn.t222.pojo.Result;
import cn.t222.pojo.SysResources;
import cn.t222.pojo.SysRole;
import cn.t222.pojo.SysUser;
import cn.t222.service.ResourceService;
import cn.t222.service.RoleService;
import cn.t222.service.UserService;
import cn.t222.util.LayuiTreeNode;
import cn.t222.util.LayuiUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.security.Principal;
import java.util.List;

@RestController
@RequestMapping("/sys")
@Slf4j
public class GrantController {
    @Resource
    private UserService userService;
    @Resource
    private RoleService roleService;
    @Resource
    private ResourceService resourceService;
    /**
     * 根据用户名显示所有用户及对应的角色
     * @param page
     * @param limit
     * @param username
     * @return
     */
    @GetMapping("/grant/get-user-roles")
    public Result userRoles(@RequestParam(defaultValue = "1") Integer page,
                            @RequestParam(defaultValue = "10") Integer limit,
                            String username) {
        PageHelper.startPage(page, limit);
        List<SysUser> list = userService.getAllByUsername(username);
        PageInfo<SysUser> pageInfo = PageInfo.of(list);
        return Result.ok("200","success", pageInfo);
    }
    @GetMapping("/grant/get-roles")
    public Result roles() {
        List<SysRole> list = roleService.getAll();
        return Result.ok("200","success", list);
    }

    @PostMapping("/grant/update-user-roles")
    public Result updateRoles(Integer userId, String roleIds) {
        String[] ids = roleIds.split(",");
        Integer[] values = new Integer[ids.length];
        for(int i = 0; i < ids.length; i++) {
            values[i] = Integer.parseInt(ids[i]);
        }
        roleService.updateRoles(userId, values);
        return Result.ok("200","success", null);
    }

    @GetMapping("/grant/get-role-resources")
    public Result resources(Integer roleId) {
        List<SysResources> resourcesList = resourceService.getAll();
        List<SysResources> checkedResourceList = resourceService.getAllByRoleId(roleId);
        List<LayuiTreeNode> nodeList = LayuiUtil.convert(resourcesList, checkedResourceList);
        if(log.isDebugEnabled()) {
            log.debug("node list:{}", nodeList);
        }
        return Result.ok("200","success", nodeList);
    }

    @PostMapping("/grant/update-role-resources")
    public Result updateResources(Integer roleId, String resourceIds) {
        resourceService.updateResources(roleId, resourceIds);
        return Result.ok("200","success", null);
    }
}
